package com.baixun.gascommon.utils;

import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class EasyExcelExportUtil {

    /**
     * 通用Excel导出方法
     *
     * @param response HttpServletResponse对象
     * @param fileName 导出文件名
     * @param clazz    Excel映射类
     * @param data     要导出的数据
     */
    public static void exportExcel(HttpServletResponse response, String fileName, Class<?> clazz, List<?> data) {
        try {
            // 设置响应内容类型和编码
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 对文件名进行编码，避免中文乱码
            String fileNameEncoded = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            // 设置下载文件的头信息
            response.setHeader("Content-disposition", "attachment;filename=" + fileNameEncoded + ".xlsx");

            // 使用EasyExcel进行写入
            EasyExcel.write(response.getOutputStream(), clazz).sheet("Sheet1").doWrite(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
